<template>
  <div class="contain-total">
    <el-header style="margin-bottom: 40px">
      <TopBar
      />
    </el-header>

    <el-container style="display: flex; flex-direction: column; align-items: center">
      <div class="container-box">
        <div class="gantt-top-container">
          <div class="search">
            <span>请输入任务标题：</span>
            <el-input placeholder="请输入任务标题" style="width: 200px" v-model="taskName" clearable>

            </el-input>
            <el-button style="margin-left: 20px; height: 30px" type="primary" @click="getGanttData">搜索</el-button>
          </div>
          <div class="excel-container">
            <el-button @click="exportData" style="height: 40px">导出excel</el-button>
          </div>
        </div>
        <div>
          <section class="my-gantt">
            <div id="gantt_here" class="gantt-container"></div>
          </section>
        </div>
      </div>
    </el-container>
  </div>


</template>

<script setup>
import {reactive, toRefs, onBeforeMount, onMounted, watchEffect, defineExpose, ref, onBeforeUnmount} from 'vue'

import {gantt} from 'dhtmlx-gantt'
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
import TopBar from "@/components/topBar.vue";
// import demoData from './ganttData.json'
import {getGantt, getGanttProject} from "@/api/task/task.js"
import {ElMessage} from "element-plus";

const data = reactive({})
const taskName = ref("")

function exportData() {
  gantt.exportToExcel({
    visual: true
  })
}

const ganttDate = ref({
  data: []
})
const zoomConfig = {
  levels: [
    [
      {unit: "year", step: 1, format: "%Y"}, // 按年显示
      {unit: "month", step: 1, format: "%M"} // 按月份显示
    ],
    [
      {unit: "month", step: 1, format: "%Y-%m"}, // 按月显示
      {unit: "day", step: 3, format: "%d 日"}
    ],
    [
      {unit: "month", step: 1, format: "%Y-%m"}, // 按月显示
      {unit: "day", step: 1, format: "%d 日"}
    ],
    [
      {unit: 'day', step: 1, format: '%M%j日'},
      {unit: "hour", format: "%H:%i", step: 5}
    ],
    [
      {unit: 'day', step: 1, format: '%M%j日'},
      {
        unit: "hour", format: "%H:%i", step: 1
      }
    ],
    [
      {unit: 'day', step: 1, format: '%M%j日'},
      {
        unit: "minute", format: "%H:%i", step: 30
      }
    ],
    [
      {unit: 'day', step: 1, format: '%M%j日'},
      {
        unit: "minute", format: "%H:%i", step: 15
      }
    ],
  ],
  useKey: "ctrlKey",
  trigger: "wheel",
  element: function () {
    return gantt.$root.querySelector(".gantt_task");
  }

}
onBeforeMount(async () => {
  await getGanttData()
})
const getGanttData = async () => {
  const res = await getGantt({
    "taskName": taskName.value,
    "isProject": 0
  })
  const res2 = await getGanttProject({
    "taskName": taskName.value
  })
  if (res.data.code === 200 && res2.data.code === 200) {
    ElMessage.success('获取数据成功')
    let data = [...res.data.result]
    const data2 = [...res2.data.result]
    data2.forEach(item => {
      item.text = item.projectName
      item.progress = 0
      item.start_date = item.projectStartTime
      item.taskStartTime = item.projectStartTime
      item.end_date = item.projectEndTime
      item.taskEndTime = item.projectEndTime
      item.open = true
      item.userNamesString = "-"
      item.state = "-"
    })

    data = data.filter(item => {
      item.text = item.taskName
      item.progress = item.process * 0.01
      item.parent = item.projectId
      item.open = true
      item.state = item.process + ""
      if (item.taskStartTime && item.taskEndTime) {
        item.start_date = item.taskStartTime;
        item.end_date = item.taskEndTime;
        return true; // 保留该项
      }
      return false; // 过滤掉不符合条件的项
    })
    ganttDate.value.data = [...data, ...data2]
    gantt.clearAll()
    gantt.addMarker({
      start_date: new Date(), // 在当前时间戳添加标记
      css: "today",
      text: "当前时间",
      title: "当前时间"
    });
    gantt.parse(ganttDate.value)   //填充数据
  } else {
    ElMessage.error('获取数据失败')
  }
}
const getNowDay = () => {
  let currentTimeInMs = Date.now();
  // 创建日期对象
  let now = new Date(currentTimeInMs);
  let hour = ('0' + now.getHours()).slice(-2); // 获取当前小时数（0-23）并确保为两位数
  let minute = ('0' + now.getMinutes()).slice(-2); // 获取当前分钟数（0-59）并确保为两位数
  let second = ('0' + now.getSeconds()).slice(-2); // 获取当前秒数（0-59）并确保为两位数
  // 格式化为字符串
  return `${hour}:${minute}:${second}`;
}
//初始化甘特图
const initGantt = () => {
  gantt.config.grid_width = 350
  gantt.config.add_column = false //添加符号
  gantt.config.scale_height = 60;
  gantt.config.fit_tasks = false; // 关闭自动调整任务时间
  gantt.config.autofit = false; // 关闭自动填充


  gantt.config.columns = [
    {name: 'text', label: '项目名称', tree: true, width: '100', align: 'center'},
    {name: 'state', label: '任务进度（%）', width: '100', align: 'center'},
    {name: 'userNamesString', label: '任务成员', width: '100', align: 'center'},
    {name: 'taskStartTime', label: '任务/项目开始时间', width: '150', align: 'center'},
    {name: 'taskEndTime', label: '任务/项目结束时间', width: '150', align: 'center'},

  ]

  //时间轴图表中，如果不设置，只有行边框，区分上下的任务，设置之后带有列的边框，整个时间轴变成格子状。
  gantt.config.autofit = false
  gantt.config.row_height = 60
  gantt.config.bar_height = 34
  // gantt.config.fit_tasks = true //自动延长时间刻度，以适应所有显示的任务
  gantt.config.auto_types = true //将包含子任务的任务转换为项目，将没有子任务的项目转换回任务
  gantt.config.readonly = true //是否只读
  gantt.i18n.setLocale('cn') //设置语言
  gantt.templates.parse_date = function (dateString) {
    return new Date(dateString);
  };

  gantt.templates.format_date = function (date) {
    return date.toISOString();
  };

  gantt.plugins({
    export_api: true,
    marker: true,
    tooltip: true,
    zoom: true
  });
  gantt.addMarker({
    start_date: new Date(), // 在当前时间戳添加标记
    css: "today",
    text: "当前时间",
    title: "当前时间"
  });
  gantt.templates.tooltip_text = (start, end, task) => {
    let tooltips = [];
    tooltips.push("任务名称: " + task.text);
    if (task.parent !== 0){
      tooltips.push(`进度: ${
          task.state === "100"
              ? `<span style="color:green">${task.state}%</span>`
              : `<span style="color:#e74c3c">${task.state}%</span>`
      }`);
      tooltips.push("任务成员: " + task.userNamesString);
    }
    tooltips.push("开始时间: " + task.taskStartTime);
    tooltips.push("结束时间: " + task.taskEndTime);
    return `<div>
        ${tooltips.join('<br>')}
    </div>`;
  };

  gantt.templates.progress_text = (start, end, task) => {
    if (task.parent !== 0 && task.state !== 100){
      return task.state + "%"
    }
  }
// task 自定义样式
  gantt.templates.task_class = function (start, end, task) {
    if (task.parent === 0){
      return "project_timeline"
    }
  };
  gantt.init('gantt_here')  //初始化
  // gantt.clearAll()
  gantt.parse(ganttDate.value)   //填充数据
  gantt.ext.zoom.init(zoomConfig);

}

onMounted(() => {
  initGantt()
})


</script>
<style scoped>
.my-gantt {
  height: 600px;
  margin-top: 20px;

  .gantt-container {
    width: 100%;
    height: 100%;
  }
}
:deep(.gantt_tooltip){
  background-color: #31ccd2 !important;
}
/* 工具提示容器 */
:deep(.custom-tooltip-wrapper) {
  background: #2c3e50 !important;  /* 修改背景颜色 */
  border: 2px solid #3498db !important;  /* 修改边框 */
  border-radius: 8px !important;  /* 圆角 */
  box-shadow: 0 4px 12px rgba(0,0,0,0.2) !important;  /* 添加阴影 */
  color: #ecf0f1 !important;  /* 文字颜色 */
  font-family: 'Arial', sans-serif !important;  /* 字体 */
  font-size: 14px !important;  /* 字体大小 */
  padding: 15px !important;  /* 内边距 */
  max-width: 400px !important;  /* 最大宽度 */
}



:deep(.project_timeline) {
  background: rgba(87, 85, 85, 0.9);
}

.search {
  display: flex;
  flex-direction: row;
  justify-items: center;
  align-items: center;
}

.container-box {
  width: 1305px;
}

.container-box {
  display: flex;
  flex-direction: column;
  margin-top: 20px;
}

.gantt-top-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-items: center;
  position: relative;
}

.excel-container {
  position: absolute;
  right: 0;
}

/* 针对左侧表格头部 */
:deep(.gantt_grid_scale) {
  height: 60px !important; /* 调整表头整体高度 */
  line-height: 60px !important; /* 文字垂直居中 */
}
</style>
